package com.xjscrm.server.service.soptask.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.entity.SopTask;
import com.xjscrm.common.entity.SopTaskDevice;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.dto.soptask.SopTaskQuery;
import com.xjscrm.server.mapper.SopTaskDeviceMapper;
import com.xjscrm.server.mapper.SopTaskMapper;
import com.xjscrm.server.service.soptask.SopJobHanderService;
import com.xjscrm.server.service.soptask.SopTaskSyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 群发任务异步实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class SopTaskSyncServiceImpl implements SopTaskSyncService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SopTaskMapper sopTaskMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private SopJobHanderService sopJobHanderService;
    @Autowired
    private SopTaskDeviceMapper sopTaskDeviceMapper;

    /**
     * 处理手动SOP任务
     *
     * @param merId
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void autoSopTaskSyncByHander(@MerId Long merId) {
        //限流key
        String taskLimitKet = "-autoSopTaskSyncByHander-taskLimitKey-merId=" + merId;
        Object object = redisTemplate.opsForValue().get(taskLimitKet);
        if (object != null) {
            return;
        }
        //保存限流key
        redisTemplate.opsForValue().set(taskLimitKet, taskLimitKet, 100, TimeUnit.SECONDS);

        log.info("-----处理手动SOP任务----merId=" + merId);

        try {
            //查询当前手动SOP任务
            int now = DateUtil.getTime();

            SopTaskQuery sopTaskQuery = new SopTaskQuery();
            sopTaskQuery.setMerId(merId);
            sopTaskQuery.setType(1); //类型(1-手动sop;2-新客户sop;3-标签sop;4-群sop)
            sopTaskQuery.setStatus(1);       //进行中
            sopTaskQuery.setHanderStatus(0); //未处理

            //查询所有的自动发圈配置记录
            Page<SopTask> page = new Page<>();
            page.setCurrent(1);//只查第一页
            page.setSize(10); //每页查询10个
            page.addOrder(OrderItem.asc("id"));//默认id升序
            Long idStart = 0L;
            List<SopTask> sopTaskList = sopTaskMapper.findByList(page, sopTaskQuery);
            while (sopTaskList != null && sopTaskList.size() > 0) {
                for (SopTask sopTask : sopTaskList) {
                    if (sopTask.getId().longValue() >idStart.longValue()) {
                        idStart = sopTask.getId();
                    }

                    //限流判断
                    String rateLimitKey = "autoSopTaskSyncByHander-taskId=" + sopTask.getId();
                    Object rateLimitKeyobject = redisTemplate.opsForValue().get(rateLimitKey);
                    if (rateLimitKeyobject == null) {
                        //保存限流key
                        redisTemplate.opsForValue().set(rateLimitKey, rateLimitKey, 300, TimeUnit.SECONDS);
                    } else {
                        continue;
                    }

                    try {

                        //未处理
                        if (Tools.getInteger(sopTask.getHanderStatus()).intValue() == 0) {
                            //查询当前手动任务对于的机器人列表
                            List<SopTaskDevice> sopTaskDeviceList = sopTaskDeviceMapper.selectByTaskId(sopTask.getId());
                            if (sopTaskDeviceList != null && sopTaskDeviceList.size() > 0) {
                                for (SopTaskDevice sopTaskDevice : sopTaskDeviceList) {
                                    //处理群发任务
                                    sopJobHanderService.addSopJobByHander(sopTask.getMerId(), sopTask, sopTaskDevice);
                                }
                                //处理完成，修改已完成
                                sopTask.setUpdateTime(now);
                                sopTask.setHanderStatus(1); //已处理
                                sopTask.setHanderTime(now);
                                sopTaskMapper.updateHanderTimeById(sopTask);
                            }
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    } finally {
                        //保存成功之后，手动删除限流redisKey
                        redisTemplate.delete(rateLimitKey);
                    }
                }

                sopTaskQuery.setIdStart(idStart);
                sopTaskList = sopTaskMapper.findByList(page, sopTaskQuery);
            }
        } catch (Exception e) {
            log.info(e.getMessage(),e);
        } finally {
            //删除限流key
            redisTemplate.delete(taskLimitKet);
        }
    }

}
